<template> 
  <el-card class="form-container" shadow="never">
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="填写试题信息"></el-step>
      <el-step title="填写题目及答案"></el-step>
     
    </el-steps>
    <question-info-detail
      v-show="showStatus[0]"
      v-model="questionParam"
      :is-edit="isEdit"
      :is-disabled="isDisabled"
      @nextStep="nextStep">
    </question-info-detail>
   
    <question-attr-detail
      v-show="showStatus[1]"
      v-model="questionParam"
      :is-edit="isEdit"
      :is-disabled="isDisabled"
      @finishCommit="finishCommit"
      @prevStep="prevStep">
    </question-attr-detail>
    
  </el-card>
</template>
<script>
  import {mapGetters} from 'vuex'
  import store from '@/store'
  import QuestionInfoDetail from './QuestionInfoDetail';
 
  import QuestionAttrDetail from './QuestionAttrDetail';
  
  import {createQuestion,getQuestion,updateQuestion} from '@/api/question';
  import {deepClone} from '@/utils/helper';
  

  const defaultQuestionParam = {
    //QuestionInfoDetail 页面信息
    subjectId:null,
    
    level:null,  //阶段
    difStatus: null,  //难度
    starStatus: null,  //推荐指数
    verifyStatus: 0,//审核信息有效 ；1：通过； 0:不通过；增加试题时默认为0
    validStatus: 1,//是否有效 ；1：有效； 0:无效；增加试题时默认为0
    subjectId: null,    //学科Id
    sourceId: null,    //题目来源Id
    typeId: null,    //题型
    knowledge: null,    //知识点
    comment:null,
    //questionAttrDetail页面信息
    question: '',
    answer: '',
    imgIds:'',
    
  };
  export default {
    name: 'QuestionDetail',
    components: {QuestionInfoDetail, QuestionAttrDetail},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      },
      isDisabled:{
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        active: 0,
        questionParam: Object.assign({}, defaultQuestionParam),
        showStatus: [false, false]
      }
    },
    computed :{
      ...mapGetters([
         
            'allLevelList',
            'IMG_URL'
          ]),

      /*
        level id 字典
         key=level id
         value=父level  id
        */
        levelDic : function(){
          var dic=new Array()
          let allLevelList=this.allLevelList
          for (var i=0;i<allLevelList.length;i++){
            dic[allLevelList[i].id]=allLevelList[i].parentId

          }
          return dic

        },
        
      },
    created(){
      if(this.isEdit){
        
        getQuestion(this.$route.query.id).then(response=>{
          this.questionParam=response.data;
       
          /*把传过来的level 参数"2,3,4"，变成[[1,2][1,3][1,4]]*/
          let updatelevels= response.data.level
          this.questionParam.level =[]
          
          for (var i=0;i<updatelevels.length;i++){
            this.questionParam.level.push(this.getLevelParentPath(updatelevels[i]))
          }

          /*将知识点变成叶子结点的数组*/
          //this.questionParam.knowledge=this.questionParam.knowledgeIds.split(',')

          /*替换questionParam中answer的部分*/
          this.questionParam.answer=this.replaceBackImage(this.questionParam.answer);
          this.questionParam.question=this.replaceBackImage(this.questionParam.question);



          this.showStatus[0]=true
        });

      }else{
        //增加试题
        this.showStatus[0]=true
      }

    },
    methods: {
      /*
        输入是LevelID
        输出是它的父亲节点，祖父节点...直到 ParentId=0 [],
        用于在阶段选择下拉框中选中相应的阶段
        */
        getLevelParentPath(levelId){
          
          var parentsPath=[levelId]
          var parentId=this.levelDic[levelId]
          while (parentId!=0){
            parentsPath.unshift(parentId)
            parentId=this.levelDic[parentId]

          }
          
          return parentsPath

        },

      hideAll() {
        for (let i = 0; i < this.showStatus.length; i++) {
          this.showStatus[i] = false;
        }
      },
      prevStep() {
        if (this.active > 0 && this.active < this.showStatus.length) {
          this.active--;
          this.hideAll();
          this.showStatus[this.active] = true;
        }
      },
      nextStep() {
        if (this.active < this.showStatus.length - 1) {
          this.active++;
          this.hideAll();
          this.showStatus[this.active] = true;
        }
      },

    //输入是要处理的字符串,返回的是imgid的数组
      findImageIds(toString){
        var imgIds = []
        if (toString===null) return imgIds
        var findstr = new RegExp('src="'+ this.IMG_URL+'[a-zA-Z0-9]+"',"gm")
        var  arr=toString.match(findstr)
        if (arr===null) return imgIds
        console.log(arr.length)
        arr.forEach(v => {
            var beginIndex=v.lastIndexOf("/")+1
            var sublength=v.length-beginIndex-1 //去掉最后一个引号
            var imgId=v.substr(beginIndex ,sublength) 
            imgIds.push(imgId)
          
        })
       return imgIds
      },
      //输入是要处理的字符串,返回替换的字符串
      replaceImage(toString){
        if (toString===null) return
        var newString=toString.replace(new RegExp(this.IMG_URL,"gm"),"<IMG_URL>") 

        return newString
         

      },
      //输入是要处理的字符串,返回替换的字符串
      replaceBackImage(toString){
        if (toString===null) return
        var newString=toString.replace(new RegExp("<IMG_URL>","gm"),this.IMG_URL) 

        return newString
         

      },


      finishCommit(isEdit) {
        this.$confirm('是否要提交该试题', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            var submitParam=deepClone(this.questionParam)
            
            submitParam.knowledgeIds=submitParam.knowledge.join(',')
            let leaveLevels=[]
            let level=submitParam.level
            for (var i=0;i<level.length;i++){
              leaveLevels.push(level[i][level[i].length-1])
            }
            submitParam.levelIds=leaveLevels.join(',')
           

            var question_imgIds=this.findImageIds(submitParam.question)
            var answer_imgIds=this.findImageIds(submitParam.answer)
          
            question_imgIds=question_imgIds.concat(answer_imgIds)
         

            submitParam.answer=this.replaceImage(submitParam.answer)
            submitParam.question=this.replaceImage(submitParam.question)
            submitParam.imgIds=question_imgIds.join(',')
            //submitParam.imgIds=submitParam.knowledgeIds
           
            delete submitParam.knowledge;
            delete submitParam.level;

          if(isEdit){
          
            updateQuestion(this.$route.query.id,submitParam).then(response=>{
              this.$message({
                type: 'success',
                message: '提交成功',
                duration:1000
              });
              this.$router.back();
            });
          }else{
            
            createQuestion(submitParam).then(response=>{
              this.$message({
                type: 'success',
                message: '提交成功',
                duration:1000
              });
              this.$router.back();
            });
          }
        })
      }
    },
   
  }
</script>
<style>
  .form-container {
    width: 800px;
  }
</style>


